package com.yimi.yinhepda.views.main.function_module

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.KeyEvent
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.LinearLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.pda.uce.commom.util.MyDialog
import com.pda.ym.utils.SharedPreferUtil
import com.yimi.yinhepda.R
import com.yimi.yinhepda.base.BaseFragment
import com.yimi.yinhepda.db.dao.FuncBtnTableDao
import com.yimi.yinhepda.db.table.FuncBtnTable
import com.yimi.yinhepda.entity.bean.FuncTeamEntity
import com.yimi.yinhepda.utils.Common
import com.pda.ym.utils.SoundVibratorManager
import com.yimi.yinhepda.views.main.util.GridSpacingItemDecoration
import java.sql.SQLException


/**
 * @author: lj
 * Date: 2020/3/30 10:02
 * Description:功能页
 */
open class NewFunctionFragment : BaseFragment() {

    //交接扫描
    private var scanApplicationList = mutableListOf<FuncBtnTable>()
    //库内扫描
    private var insideApplicationList= mutableListOf<FuncBtnTable>()
    //质量管理
    private var exceptionOperateApplicationList= mutableListOf<FuncBtnTable>()

    var recycleException: RecyclerView? =null;
    var recycleOperate: RecyclerView? =null;
    var rvFuncList: RecyclerView? =null;

    override fun getContentViewId(): Int {
        return R.layout.fragment_new_function
    }

    override fun getPageName(): String {
        return "新功能页"
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        //返回监听事件
        getFocus()
        initView()
        initRecycleView()
    }


    fun initView(){
        var button= view!!.findViewById<Button>(R.id.btn_add)
        button.setOnClickListener {
            val intent = Intent(activity, AddFunctionActivity::class.java)
            intent.putExtra("scanApplicationListSize",scanApplicationList.size)
            intent.putExtra("insideApplicationList",insideApplicationList.size)
            intent.putExtra("exceptionOperateApplicationListSize",exceptionOperateApplicationList.size)
            activity!!.startActivity(intent)
        }
    }

    override fun onResume() {
        super.onResume()
        exceptionOperateApplicationList = mutableListOf<FuncBtnTable>()
        insideApplicationList = mutableListOf<FuncBtnTable>()
        scanApplicationList = mutableListOf<FuncBtnTable>()
        //功能分组map
        val teamCodeMap = mutableMapOf<String, String>()
        teamCodeMap[Common.FUNC_GROUP_OPTER_CODE] = Common.FUNC_GROUP_OPTER
        teamCodeMap[Common.FUNC_GROUP_INSIDE_CODE] = Common.FUNC_GROUP_INSIDE
        teamCodeMap[Common.FUNC_GROUP_EXCEPTION_CODE] = Common.FUNC_GROUP_EXCEPTION
        //查询所有功能
        val funcList =FuncTableUtils.getList(FuncBtnTableDao().findAll())

        //列表展示分组集合
        val funcTeamEntity = mutableListOf<FuncTeamEntity>()
        teamCodeMap.forEach { map ->
            val btnList = mutableListOf<FuncBtnTable>()
            funcList?.forEach { table ->
                if (map.key == table.groupCode && table.isAdd == 1) {
                    btnList.add(table)
                }
            }
            //设置功能背景图片
            Common.setFuncPic(btnList)
            if(Common.FUNC_GROUP_OPTER==map.value){ //操作模块
                scanApplicationList.addAll(btnList)
            }
            else if(Common.FUNC_GROUP_INSIDE==map.value){ //场内操作
                insideApplicationList.addAll(btnList)
            }
            else if(Common.FUNC_GROUP_EXCEPTION==map.value){ //异常操作模块
                exceptionOperateApplicationList.addAll(btnList)
            }
            funcTeamEntity.add(FuncTeamEntity(map.value, btnList))
        }

        setAdapter()

    }

    /**
     * 返回监听
     */
    private fun getFocus() {
        view!!.isFocusableInTouchMode = true
        view!!.requestFocus()
        view!!.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
            if (event.action == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                if (exceptIsDelete) {
                    exceptIsDelete= false
                    exceptionAdapter!!.notifyDataSetChanged()
                }
                if (operateIsDelete) {
                    operateIsDelete= false
                    operateAdapter!!.notifyDataSetChanged()
                }
                if (scanIsDelete) {
                    scanIsDelete= false
                    commonScanAdapter!!.notifyDataSetChanged()
                }
                return@OnKeyListener true
            }
            false
        })
    }

    fun setGridItemDecoration(recyclerView: RecyclerView){
        val spanCount = 4 // 3 columns
        val spacing = 10 // 50px
        val includeEdge = false
        recyclerView.addItemDecoration(GridSpacingItemDecoration(spanCount, spacing, includeEdge))
    }
    var exceptionAdapter: BaseQuickAdapter<FuncBtnTable, BaseViewHolder>? = null
    var operateAdapter: BaseQuickAdapter<FuncBtnTable, BaseViewHolder>? = null
    var commonScanAdapter: BaseQuickAdapter<FuncBtnTable, BaseViewHolder>? = null

    var exceptIsDelete:Boolean= false
    var operateIsDelete:Boolean=false
    var scanIsDelete:Boolean=false
    private fun initRecycleView() {
        //异常操作
        recycleException = view!!.findViewById(R.id.recycle_exception_operate)
        recycleException!!.setLayoutManager(GridLayoutManager(activity, 4))
        setGridItemDecoration(recycleException!!)

        //场内操作
         recycleOperate = view!!.findViewById(R.id.recycle_operate)
        recycleOperate!!.setLayoutManager(GridLayoutManager(activity, 4))
        setGridItemDecoration(recycleOperate!!)

        //扫描
         rvFuncList = view!!.findViewById(R.id.rv_func_list)
        rvFuncList!!.setLayoutManager(GridLayoutManager(activity, 4))
        setGridItemDecoration(rvFuncList!!)

    }



   fun setAdapter(){
       exceptionAdapter = object : BaseQuickAdapter<FuncBtnTable, BaseViewHolder>(R.layout.item_func_child, exceptionOperateApplicationList) {
           override fun convert(helper: BaseViewHolder?,  item: FuncBtnTable?, postion: Int) {
               helper!!.setText(R.id.tv_func_name, item!!.name)
               helper.setImageResource(R.id.iv_func_pic, item.picId)
               helper.convertView.tag = postion
               setDeleteView(exceptIsDelete,helper,postion,mContext)
               setViewEnabled(helper,item)

               itemOnclickListener(exceptIsDelete,helper,item,exceptionAdapter,exceptionOperateApplicationList)

               helper.getConvertView().setOnLongClickListener(object:View.OnLongClickListener{
                   override fun onLongClick(v: View?): Boolean {
                       exceptIsDelete=!exceptIsDelete
                       SoundVibratorManager.playVibrator(context, 70)
                       notifyDataSetChanged()
                       return true
                   }
               })
           }
       }
       recycleException!!.setAdapter(exceptionAdapter)

       operateAdapter = object : BaseQuickAdapter<FuncBtnTable, BaseViewHolder>(R.layout.item_func_child,insideApplicationList) {
           override fun convert(helper: BaseViewHolder?, item: FuncBtnTable?, postion: Int) {
               setDeleteView(operateIsDelete,helper,postion,mContext)
               setViewEnabled(helper,item)
               helper!!.setText(R.id.tv_func_name, item!!.name)
               helper.setImageResource(R.id.iv_func_pic, item.picId)
               helper.convertView.tag = postion

               itemOnclickListener(operateIsDelete,helper,item,operateAdapter,insideApplicationList)

               helper.getConvertView().setOnLongClickListener(object:View.OnLongClickListener{
                   override fun onLongClick(v: View?): Boolean {
                       operateIsDelete=!operateIsDelete
                       SoundVibratorManager.playVibrator(context, 70)
                       notifyDataSetChanged()
                       return true
                   }
               })
           }
       }
       recycleOperate!!.setAdapter(operateAdapter)

       commonScanAdapter = object : BaseQuickAdapter<FuncBtnTable, BaseViewHolder>(R.layout.item_func_child, scanApplicationList) {

           override fun convert(helper: BaseViewHolder?, item: FuncBtnTable?, postion: Int) {
               helper!!.setText(R.id.tv_func_name, item!!.name)
               helper.setImageResource(R.id.iv_func_pic, item.picId)
               helper.convertView.tag = postion

               setDeleteView(scanIsDelete,helper,postion,mContext)
               setViewEnabled(helper,item)

               itemOnclickListener(scanIsDelete,helper,item,commonScanAdapter,scanApplicationList)

               helper.getConvertView().setOnLongClickListener(object:View.OnLongClickListener{
                   override fun onLongClick(v: View?): Boolean {
                       scanIsDelete=!scanIsDelete
                       SoundVibratorManager.playVibrator(context, 70)
                       notifyDataSetChanged()
                       return true
                   }
               })
           }
       }
       rvFuncList!!.setAdapter(commonScanAdapter)
   }

    fun setViewEnabled(helper: BaseViewHolder?, item: FuncBtnTable?){
        val llFuncBtn: LinearLayout = helper!!.getView(R.id.ll_func_btn)
        val deptType = SharedPreferUtil.getInstance().getIntValue(Common.DEPT_TYPE)
        if (deptType == 5 || deptType == 6) {
            if (item!!.getNameCode() == Common.FUNC_QDGL || item.getNameCode() == Common.FUNC_LHSM) { //分拨屏蔽签到管理、揽货扫描
                llFuncBtn.isEnabled = false
            } else {
                llFuncBtn.isEnabled = true
            }
        } else {
            if (item!!.getNameCode() == Common.FUNC_FBZT) { //网点屏蔽分拨自提
                llFuncBtn.isEnabled = false
            } else {
                llFuncBtn.isEnabled = true
            }
        }
    }


    fun setDeleteView(isDelete:Boolean,helper: BaseViewHolder?,postion: Int,mContext:Context){
        if (isDelete){
            //显示删除按钮
            helper!!.setVisible(R.id.iv_delete_btn,true)
            val shake: Animation
            shake = if (postion % 2 == 1) {
                AnimationUtils.loadAnimation(mContext, R.anim.anim_func)
            } else {
                AnimationUtils.loadAnimation(mContext, R.anim.anim_func2)
            }
            shake.reset()
            shake.fillAfter = true
            helper.itemView.startAnimation(shake)
        }
        else{
            helper!!.setVisible(R.id.iv_delete_btn,false)
        }
    }


    fun itemOnclickListener(isDelete:Boolean,helper: BaseViewHolder?,item: FuncBtnTable?,dataAdapter: BaseQuickAdapter<FuncBtnTable, BaseViewHolder>?,dataList:MutableList<FuncBtnTable>){
        helper!!.getConvertView().setOnClickListener(object:View.OnClickListener{
            override fun onClick(v: View?) {
                if (isDelete){
                    //显示删除按钮时提示删除
                    MyDialog.showAlertDialog(context, "确定删除？", "确定", "取消",
                            { dialog, _ ->
                                dialog.dismiss()
                                try {
                                    //设置为未添加状态
                                    item!!.isAdd = 0
                                    val result = FuncBtnTableDao().update(item)
                                    if (result != -1) {
                                        //移除列表缓存
                                        dataList.remove(item)
                                        dataAdapter!!.notifyDataSetChanged()
                                    }
                                } catch (e: SQLException) {
                                    e.printStackTrace()
                                }
                            },
                            { dialog, _ -> dialog.dismiss() })
                }
                else{
                    //点击跳转
                    val llFuncBtn = helper.getView<LinearLayout>(R.id.ll_func_btn)
                    if (llFuncBtn.isEnabled) {
                        goToActivity(item)
                    }
                }
            }

        })
    }


}